<template>
  <div class="app-container">
    <my-tree-selector-query
      ref="regionTree"
      title="部署区域"
      :current-node-key="this.filter.data.regionId"
      :default-expanded-keys="[this.filter.data.regionId]"
      :options="regionDataOptions"
      :treeProps="{ children: 'children',label: 'name'}"
      @click-node="handleNodeClick"
    />
    <div class="right-wrap">
      <u-page-config
        ref="pageConfig"
        :filter-array="filterArray"
        v-model="filter"
        :actionBtn="actionBtn"
        label-width="124px"
        :getList="getList"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="total"
        :loading="loading"
        :selectable="selectableFn"
        showSelection
        @handleSelectionChange="handleSelectionChange"
        @handleSelectionAll="handleSelectionAll"
        @addUpdatePlan="addUpdatePlan"
      >
        <template #groupId="{item}">
          <treeselect
            v-model="filter.data.groupId"
            :options="groupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择分组"
            style="width: 240px"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </template>

        <template #deviceStatus="scope">
          <dict-tag
            :options="dict.type.device_status"
            :value="scope.row.deviceStatus"
          />
        </template>
      </u-page-config>
    </div>
    <module-update-select
      v-if="visible"
      v-model="visible"
      :deviceCode="currentSelectedDeviceCode"
      :deviceIds="selectedDeviceIds"
    />
  </div>
</template>

<script>
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
import table from "@/mixin/uTable";
import UPageConfig from "@/components/uPageConfig/index";
import UForm from "@/components/uForm/index";
import Treeselect from "@riophae/vue-treeselect";
import {listManager} from "@/api/device/placeManager";
import {listGroup} from "@/api/device/group";
import {handleTree} from "@/utils/ruoyi";
import ModuleUpdateSelect from "./components/moduleUpdateSelect"

export default {
  name: "UpdatePlan",
  mixins: [table],
  dicts: ['device_status'],
  components: {
    UPageConfig,
    MyTreeSelectorQuery,
    Treeselect,
    ModuleUpdateSelect
  },
  data() {
    return {
      filterArray: [
        {label: "部署名称", key: "deploymentName", type: "input"},
        {label: "设备ID", key: "operationUserCode", type: "input"},
        {label: "设备型号", key: "deviceName", type: "input"},
        {label: "部署分组", key: "groupId", type: "slot", slot: 'groupId'},
        {label: "设备状态", key: "deviceStatus", type: "select", options: []},
      ],
      tableColumn: [
        {label: "设备ID", prop: "deviceId"},
        {label: "设备部署名称", prop: "deploymentName"},
        {label: "设备型号", prop: "deviceName"},
        {label: "设备编码", prop: "deviceCode"},
        {label: "部署分组", prop: "groupName"},
        {label: "状态", prop: "orderStatus", type: 'slot', slot: 'deviceStatus'},
      ],
      actionBtn: [
        {
          type: 'primary',
          text: '创建更新计划',
          icon: 'el-icon-folder-add',
          emit: 'addUpdatePlan',
          disabledRule: () => this.selectedDeviceIds.length === 0
        }
      ],
      // 表单默认必填参数 重置表单时需要用到
      defaultForm: {
        deviceId: '',
        deploymentName: '',
        deploymentCode: '',
        operationUserCode: '',
        message: '',
        image: '',
        reportName: '',
        reportPhone: '',
      },
      formArray: [
        {
          label: "计划执行时间：", key: "executionTime", col: 24, type: "timerrange",
          rule: {required: true, message: '更新计划执行时间不能为空！', trigger: 'blur'},
        },
      ],
      // 查看详情表单配置
      detailArray: [
        {
          label: "设备ID：", key: "deviceId", col: 24, type: "text",
        },
        {label: "部署名称：", key: "deploymentName", col: 24, type: "text", placeholder: ' '},
        {
          label: "运维人员：", key: "operationUserCode", col: 24, type: "select", options: [],
        },
        {label: "问题描述：", key: "message", col: 24, type: "text", attr: {resize: 'none'}},
        {label: "照片：", key: "image", col: 24, type: "img"},
        {
          label: "报障人联系电话：", key: "reportPhone", col: 24, type: "text",
        },
        {
          label: "报障人姓名：", key: "reportName", col: 24, type: "text",
        },
      ],
      // 分组选项
      groupOptions: [],
      // 当前勾选中的设备id
      selectedDeviceIds: [],
      // 当前选中的设备编码
      currentSelectedDeviceCode: '',
      // 禁用表格前面多选框方法
      selectableFn: null
    }
  },
  computed: {
    //默认显示省份ID
    provinceIdConfig() {
      return this.$store.state.app.provinceIdConfig
    },
    // 所有地区树形数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions;
    },
    //有效的品牌，用于下拉列表
    brands() {
      return this.$store.state.device.brands || []
    },
  },
  methods: {
    /** 转换区域树形图数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 点击区域节点
    getChildrenRegion(id, options) {
      //是否还没找到，继续循环
      let going = true;
      let result = []
      let walker = (id, array) => {
        array.forEach(item => {
          if (!going) return;
          if (item['id'] === id) {
            going = false;
            result = [item];
          } else if (item['children']) {
            walker(id, item['children']);
          }
        });
      }
      walker(id, options)
      return result
    },
    /** 查询区域包含的分组管理列表 */
    getRegionGroup(regionId) {
      this.loading = true;
      listGroup({regionId}).then(res => {
        this.groupOptions = handleTree(res.rows, "id");
      }).finally(() => {
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.filter.data.regionId = data.id;
      // 清空选择的分组
      this.getRegionGroup(data.id)
      this.getList();
    },
    // 表单提交接口相关配置
    formSubmitFunConfig() {
      return {
        addFunc: () => {
        },
        modifyFunc: () => {
        },
        pk: 'id',
        options: {
          ...this.form
        },
        cbFunc: () => {
          this.visible = false
        }
      }
    },
    // 选中全部
    handleSelectionAll(selection) {
      const tableRef = this.$refs.pageConfig.$children[2].$refs.table
      if (selection.length) { //全选
        const firstItem = selection[0];
        // 取消激活不是和第0个设备相同设备编码的勾选
        this.tableData.forEach(item => {
          if (item.deviceCode !== firstItem.deviceCode) {
            tableRef.toggleRowSelection(item, false);
          }
        })
        // 进行筛选 默认选中列表第一个相同设备型号的行
        this.selectedDeviceIds = selection.map(item => item.deviceId);
        this.currentSelectedDeviceCode = selection[0].deviceCode;
      } else {
        this.selectedDeviceIds = [];
        this.currentSelectedDeviceCode = '';
      }
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      const selectionLength = selection.length;
      if (selectionLength) {
        this.currentSelectedDeviceCode = selection[0].deviceCode;
      }else{
        this.currentSelectedDeviceCode = '';
      }
      this.selectedDeviceIds = selection.map(item => item.deviceId);
    },
    /** 查询工单列表 */
    getList() {
      // 如果点击了重置按钮，regionId被清空后，自动赋值为默认省份id
      if(!this.filter.data.regionId){
        this.filter.data.regionId = this.provinceIdConfig;
        this.$refs.regionTree.$refs.tree.setCurrentKey(this.provinceIdConfig);
      }
      // 获取列表
      this.getInit(listManager, {})
    },
    /** 详细按钮操作 */
    addUpdatePlan() {
      this.visible = true;
    },
    /** 返回设备部署页面 */
    goBack() {
      this.$router.go(-1);
    },
  },
  watch: {
    'dict.type.device_status': {
      handler(newValue) {
        // 设置设备状态选项数据
        try {
          this.filterArray.find(item => item.key === 'deviceStatus').options = newValue;
        } catch (e) {
          console.log("找不到对应表单项", e)
        }
      },
    },
  },
  created() {
    this.selectableFn = (row) => {
      return !this.currentSelectedDeviceCode || row.deviceCode === this.currentSelectedDeviceCode
    }
    // 设置默认选择区域
    this.filter.data.regionId = this.provinceIdConfig;
    // 获取分组
    this.getRegionGroup(this.provinceIdConfig);
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  min-height: inherit;

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .head-card-wrap {
      display: flex;
      width: 100%;
      min-width: 850px;
      margin-bottom: 20px;
      border: 1px solid #409eff;
      border-radius: 2px;
      background: #fff;
      box-shadow: 0 2px 8px -2px rgb(0, 0, 0, 10%);

      .card-item {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 75px;
        width: 25%;
        font-size: 16px;

        .name {
          display: flex;
          align-items: center;

          .circle {
            width: 12px;
            height: 12px;
            margin-right: 5px;
            border-radius: 50%;
            background: greenyellow;
          }
        }

        .value {
          margin-top: 8px;
          font-size: 20px;

          span {
            font-size: 18px;
          }
        }

        &:last-child {
          &::after {
            width: 0;
          }
        }

        &::after {
          position: absolute;
          content: '';
          right: 0;
          top: 50%;
          width: 1px;
          height: 60%;
          background: #409eff;
          transform: translateY(-50%);
        }
      }
    }
  }

}
</style>
